package demo4.mapper;

import com.alibaba.druid.pool.DruidDataSource;
import demo4.config.DBUtil;
import demo4.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Component
public class UserMapper implements IUserMapper {
    @Autowired
    private DruidDataSource dataSource;//依赖连接池，希望Spring容器将连接池注入进来
    @Override
    public int insert(User user) {
        try (Connection connection = dataSource.getConnection();){
            String sql = "Insert into user(username,password,nickname,age)" + "values(?,?,?,?)";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getNickname());
            ps.setInt(4,user.getAge());
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public User selectByUsername(String username) {
        try (Connection connection = dataSource.getConnection();){
            String sql = "select * from user where username=?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setNickname(rs.getString("nickname"));
                user.setAge(rs.getInt("age"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
